#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
#include <string>
#include "Spline.hpp"
#include "Curvefitting.hpp"
#define PI 3.14159265358979323846

// 定义曲线 r2(t) 的 x(t) 和 y(t) 部分
class Fx : public Function {
public:
    double operator() (double t) const override {
        return sin(t) + t * cos(t);
    }
};

class Fy : public Function {
public:
    double operator() (double t) const override {
        return cos(t) - t * sin(t);
    }
};

// 生成拟合数据并保存到文件
void generate_fitting_data(int n, const std::string& filename, bool equidistant) {
    std::vector<double> X(n + 1);
    std::vector<double> Y(n + 1);
    std::vector<double> T(n + 1);

    Fx fx;
    Fy fy;

    double t_min = 0.0;
    double t_max = 6.0 * PI;

    // 生成原始点
    for (int i = 0; i <= n; ++i) {
        T[i] = t_min + i * (t_max - t_min) / n; // 参数 t 等距分布
        X[i] = fx(T[i]);
        Y[i] = fy(T[i]);
    }

    // 根据 equidistant 决定使用等距节点法或累积弦长法
    std::vector<std::vector<double>> result;
    if (equidistant) {
        result = Curve_Fitting_Equidistantnode_r2(X, Y, T);
    } else {
        result = Curve_Fitting_cumulativechordal_length_r2(X, Y, T);
    }

    // 保存拟合结果到文件
    const std::vector<double>& x_spline = result[0];
    const std::vector<double>& y_spline = result[1];

    std::ofstream file(filename);
    if (file.is_open()) {
        for (size_t i = 0; i < x_spline.size(); ++i) {
            file << x_spline[i] << ", " << y_spline[i] << std::endl;
        }
        file.close();
        std::cout << "Fitted spline points saved to " << filename << std::endl;
    } else {
        std::cerr << "Failed to open file " << filename << std::endl;
    }
}

int main() {
    // 使用等距节点和累积弦长分别拟合，生成 N = 10, 40, 160 的结果
    for (int n : {10, 40, 160}) {
        generate_fitting_data(n, "E2_fitted_equidistant_N" + std::to_string(n) + ".txt", true);
        generate_fitting_data(n, "E2_fitted_chordal_N" + std::to_string(n) + ".txt", false);
    }
    return 0;
}
